package org.momonga1banchi.reminder.server;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import java.util.TimeZone;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.momonga1banchi.reminder.util.MyLog;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

/**
 * リマインド送信サーブレット
 *
 * @author momonga1banchi
 * @since 2010/05/18
 */
@SuppressWarnings("serial")
public class ReminderServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MINUTE, -5);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        sdf.setTimeZone(TimeZone.getTimeZone("JST"));
        String fromDate = sdf.format(cal.getTime());
        cal.add(Calendar.MINUTE, 5);
        String toDate = sdf.format(cal.getTime());

        Query query = new Query("task");
        query.addFilter("date", Query.FilterOperator.GREATER_THAN_OR_EQUAL, fromDate);
        query.addFilter("date", Query.FilterOperator.LESS_THAN_OR_EQUAL, toDate);
        query.addFilter("done", Query.FilterOperator.EQUAL, false);
        PreparedQuery prepare = ds.prepare(query);
        List<Entity> resultList = prepare.asList(FetchOptions.Builder.withDefaults());

        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        for (Entity result : resultList) {
            try {
                String msgBody = result.getProperty("name").toString();
                MimeMessage msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress("reminder@scotethu.com",
                        "reminder@scotethu.com"));
                msg.setRecipient(Message.RecipientType.TO, new InternetAddress(result.getProperty("to").toString()));
                if (msgBody.length() > 10) {
                    msg.setSubject(msgBody.replaceAll("\r|\n|\r\n", " ").substring(0, 10), "iso-2022-jp");
                } else {
                    msg.setSubject(msgBody.replaceAll("\r|\n|\r\n", " "), "iso-2022-jp");
                }
                msg.setText(msgBody, "iso-2022-jp");
                Transport.send(msg);

                result.setProperty("done", true);
                ds.put(result);

            } catch (MessagingException e) {
//                MyLog.log.warn("error occured " + e.getMessage());
            }

        }
    }

}
